package com.yanboo.generator.rest;

import com.yanboo.common.annotation.CustomController;
import com.yanboo.generator.config.DynamicRoutingDataSource;
import com.yanboo.generator.domain.ColumnInfo;
import com.yanboo.generator.domain.vo.TableInfo;
import com.yanboo.generator.service.GenConfigService;
import com.yanboo.generator.service.GeneratorService;
import com.yanboo.generator.service.ProjectInfoService;
import com.yanboo.generator.service.dto.ProjectInfoDto;
import com.yanboo.generator.service.dto.ProjectInfoQueryCriteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import com.yanboo.common.exception.BadRequestException;
import com.yanboo.common.utils.PageResult;
import com.yanboo.common.utils.PageUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.util.List;

/**
 *
 */
@CustomController
@RequiredArgsConstructor
@RequestMapping("/api/generator")
@Tag(name = "系统：代码生成管理")
public class GeneratorController {

    private final GeneratorService generatorService;
    private final GenConfigService genConfigService;

    @Value("${generator.enabled}")
    private Boolean generatorEnabled;

    @Operation(summary = "查询数据库数据")
    @GetMapping(value = "/tables/all")
    public ResponseEntity<Object> queryAllTables() {
        return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK);
    }

    @Operation(summary = "查询数据库数据")
    @GetMapping(value = {"/tables/{project}","/tables"})
    public ResponseEntity<PageResult<TableInfo>> queryTables(
                                                             @RequestParam(required = false) String project,
                                                             @RequestParam(defaultValue = "") String name,
                                                             @RequestParam(defaultValue = "0") Integer page,
                                                             @RequestParam(defaultValue = "10") Integer size) {
        int[] startEnd = PageUtil.transToStartEnd(page, size);
        return new ResponseEntity<>(generatorService.getTables(project,name, startEnd), HttpStatus.OK);
    }

    @Operation(summary = "查询字段数据")
    @GetMapping(value = "/columns")
    public ResponseEntity<PageResult<ColumnInfo>> queryColumns(@RequestParam String project, @RequestParam String tableName) {
        List<ColumnInfo> columnInfos = generatorService.getColumns(project, tableName);
        return new ResponseEntity<>(PageUtil.toPage(columnInfos, columnInfos.size()), HttpStatus.OK);
    }

    @Operation(summary = "保存字段数据")
    @PutMapping
    public ResponseEntity<HttpStatus> saveColumn( @RequestBody List<ColumnInfo> columnInfos) {
        generatorService.save(columnInfos);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Operation(summary = "同步字段数据")
    @PostMapping(value = "sync/{project}")
    public ResponseEntity<HttpStatus> syncColumn(@PathVariable String project, @RequestBody List<String> tables) {
        //TODO 同步前切换数据源
        for (String table : tables) {
            generatorService.sync(generatorService.getColumns(project, table), generatorService.query(project, table));
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }

    @Autowired
    ProjectInfoService projectInfoService;

    @Autowired
    DynamicRoutingDataSource dynamicRoutingDataSource;

    @Operation(summary = "生成代码")
    @PostMapping(value = "/{project}/{tableName}/{type}")
    public ResponseEntity<Object> generatorCode(@PathVariable String project, @PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response) {
        if (!generatorEnabled && type == 0) {
            throw new BadRequestException("此环境不允许生成代码，请选择预览或者下载查看！");
        }
        List<ProjectInfoDto> projectInfoDtos = projectInfoService.queryAll(new ProjectInfoQueryCriteria().setCode(project));
        switch (type) {
            // 生成代码
            case 0:
                generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(project, tableName));
                break;
            // 预览
            case 1:
                return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(project, tableName));
            // 打包
            case 2:
                generatorService.download(genConfigService.find(tableName), generatorService.getColumns(project, tableName), request, response);
                break;
            default:
                throw new BadRequestException("没有这个选项");
        }
        return new ResponseEntity<>(HttpStatus.OK);
    }
}
